<?php

namespace App\Admin\Controllers;

use App\Models\JumpTag;
use App\Models\Settings;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Tab;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class MiniProgramSingleImgController extends AdminController
{
    const GROUP = 'special';

    public function index(Content $content)
    {
        $slug = request()->input('mini_type');

        $tab = Tab::make();
        $tab->addLink('首页模块管理', admin_route('mini_program_special.index', ['mini_type' => $slug]));
        $tab->addLink('底部菜单管理', admin_route('mini_program_tab.index', ['mini_type' => $slug]));
        $tab->addLink('首页导航', admin_route('mini_main_tab.index', ['mini_type' => $slug]));
        $tab->addLink('小程序导航', admin_route('mini_main_nav.index', ['mini_type' => $slug]));
        $tab->addLink('轮播图设置', admin_route('mini_rotation_chat.index', ['mini_type' => $slug]));
        $tab->add('轮播图设置', $this->grid(), true);
        return $content->body($tab->withCard());
    }

    protected function grid()
    {
        $form = new Form();

        $form->action(admin_route('mini_single_img.store'));

        $slug = request()->input('mini_type');
        $settings = getMiniSettings($slug, self::GROUP);

        $form->hidden('mini_type')->value($slug);

        $data = $settings['single_img'] ?? '';
        if ($data) {
            $data = json_decode($data, true) ?: [];
        } else {
            $data = [];
        }

        $form->image('img', '图片')->url('upload/files')->uniqueName()->autoUpload()->saveFullUrl()->value($data['img'] ?? '');
        $form->select('jump_id', '跳转标签')->options(JumpTag::where('is_show', 1)->pluck('name', 'id')->all())->value($data['jump_id'] ?? '');

        $form->disableHeader();
        $form->disableResetButton();
        $form->disableEditingCheck();
        $form->disableCreatingCheck();
        $form->disableViewCheck();

        return $form;
    }

    public function store()
    {
        $type = request()->input('mini_type');
        $img = request()->input('img');
        $jumpId = request()->input('jump_id');

        if (!Str::startsWith($img, ['http://', 'https://', '://'])) {
            $img = Storage::disk(config('admin.upload.disk'))->url($img);
        }

        Settings::updateOrCreate([
            'group'     => self::GROUP,
            'name'      => 'single_img',
            'mini_type' => $type,
        ], ['value' => json_encode(['img' => $img, 'jump_id' => $jumpId])]);

        flushMiniSettings($type, self::GROUP);

        return JsonResponse::make()->success('保存成功');
    }
}
